<?php 
class CrmTransactionController extends Zone_Action{
	public function field(){
		$data = array(
			date_updated =>array(
				type			=> 'NONE',
				default_value   => new Model_Expr('NOW()')
			),
			updated_by_id =>array(
				type			=> 'NONE',
				default_value 	=> get_user_id()
			),
						
			title 	=> array(
				type 			=> 'CHAR',
				no_empty 		=> true,
				form_label		=> 'Tiêu đề'
			),
			desc 	=> array(
				type 			=> 'CHAR',
				form_label		=> 'Mô tả'
			),
			'date' 	=> array(
				type 			=> 'DATE',
				form_label		=> 'Giao dịch',
				fix_value		=> change_date_format
			),			
			customer_id 	=> array(
				type 			=> 'INT',
				form_label		=> 'Công ty'
			),			
			parent_id 	=> array(
				type 			=> 'INT',
				form_label		=> 'Loại giao dịch'
			)		
		);
		return $data;	
	}
	private function getOptions(){
		$this->set(array(
			cats => $this->Model->fetchAll("SELECT * FROM `crm_transaction_types` ORDER BY `title`")		
		));
	}	
	
	private function validData( $data ){
		if( !is_array( $data ) )
			return $data;
		return $data;
	}

	public function initAction(){
		$this->removeLayout();
	}
	
	public function addAction(){
		$user_id = get_user_id();	
		$this->getOptions();
		
		if(!isPost()){
			$cus_ids = get('customer_id',array(),true);
			if( count($cus_ids) > 0 ){
				$x=array();
				foreach( $cus_ids as $k ){
					$x[] = "'$k'";
				}
				
				$x = array_unique($x);
				$x = implode(',',$x);
				
				if( $this->hasRole('crm_admin') ){
					$customers = $this->Model->fetchAll("SELECT `name`,`ID` FROM `crm_customers`
						WHERE `ID` IN ($x) AND `is_draft`='no'");	
				}else{
					$customers = $this->Model->fetchAll("SELECT `name`,`ID` FROM `crm_customers`
						WHERE `ID` IN ($x) AND `is_draft`='no' AND '$user_id' IN (`created_by_id`,`care_by_id`)");
				}	
				
				$this->set(array(
					customers => $customers
				));				
			}		
		}		
		
		if(isPost()){		
			$meta = array();
			$items = get('title',array(),true);
			foreach( $items as $k => $s ){
				loadClass('ZData');
				$f = new ZData();
				$f->addFields( $this->field());
				$f->setIndexItem($k);
				
				$data = $f->getData();
				$data = $this->validData( $data );
				
				if( !is_array($data)){
					return $this->setJSON(array(
						alert => error($data)
					));
				}		
				
				$data['date_created']  = new Model_Expr('NOW()');				
				$data['created_by_id']  = get_user_id();				
				$meta[] = $data;
			}
			
		
			if( count($meta ) ){				
				$cus_ids = get('customer_id',array(),true);
				if( count($cus_ids) > 0 ){
					$x=array();
					foreach( $cus_ids as $k ){
						$x[] = "'$k'";
					}
					
					$x = array_unique($x);
					$x = implode(',',$x);
					
					if( $this->hasRole('crm_admin') ){
						$customers = $this->Model->fetchAll("SELECT `name`,`ID` FROM `crm_customers`
							WHERE `ID` IN ($x) AND `is_draft`='no'");	
					}else{
						$customers = $this->Model->fetchAll("SELECT `name`,`ID` FROM `crm_customers`
							WHERE `ID` IN ($x) AND `is_draft`='no' AND '$user_id' IN (`created_by_id`,`care_by_id`)");
					}	
					
					foreach( $meta as $dt ){
						foreach( $customers as $cus ){
							$dt['customer_id'] = $cus['ID'];
							$this->Model->insert('crm_transactions',$dt);
						}
					}			
				}	
			}
			
			return $this->setJSON(array(
				close	=> true,
				redirect	=> '#'.get('redirect','Crm/Customer')
			));
		}
	}

	public function editAction(){
		$post_id = getInt('ID',0);
		$user_id = get_user_id();
				
		$post = $this
			->Model
			->fetchRow("SELECT * FROM `crm_transactions` WHERE `ID`='$post_id'");
		
		if(!$post){
			return $this->setJSON(array(
				alert => 'Bản ghi đã bị xóa hoặc không tồn tại'
			));
		}	
		
		if( !$this->hasRole('crm_admin') ){
			$customer = $this->Model->fetchRow("SELECT * 
				FROM `crm_customers` WHERE `ID`='{$post['customer_id']}' AND `is_draft`='no'");
			
			if( !customer ){
				return $this->setJSON(array(
					alert => 'Bản ghi đã bị xóa hoặc không tồn tại'
				));
			}
			
			if( $post['care_by_id'] != $user_id  ){
				return $this->setJSON(array(
					alert => 'Bạn không có quyền sửa bản ghi này'
				));
			}
		}
		
		if( !isPost() ){			
			$this->getOptions();			
			$this->set(array(
				ID	 => $post_id,
				post => $post
			));
		}else{
			loadClass('ZData');			
			$f = new ZData();
			
			$fields	= $this->field();
			unset($fields['customer_id']);
			
			$f->addFields($fields);

			$data = $f->getData();
			$data = $this->validData( $data );
			
			if( !is_array($data)){
				return $this->setJSON(array(
					message => error($data)
				));
			}		
		
			$this->Model->update('crm_transactions',$data,"`ID`='$post_id'");
			
			return $this->setJSON(array(
				close	 => true,
				redirect => '#'.get('redirect','Crm/Customer/View?ID='.$post['customer_id'])
			));
		}
	}

	public function deleteAction(){
	
		$ids = get('ID',array(),true);
		$user_id = get_user_id();
		
		foreach( $ids as $post_id ){
			$post = $this->Model->fetchRow("SELECT * FROM `crm_transactions` WHERE `ID`='$post_id'");
			if( !$post  ){	continue;	}
			
			if( !$this->hasRole('crm_admin') ){
				$customer = $this->Model->fetchRow("SELECT * 
					FROM `crm_customers` WHERE `ID`='{$post['customer_id']}' AND `is_draft`='no'");
				
				if( !$customer || $customer['care_by_id'] != $user_id  ){
					continue;
				}
			}
			
			$this->Model->delete('crm_transactions'," `ID`='$post_id' ");
		}
		
		return $this->setJSON(array(
			redirect => '#'.get('redirect','Crm/Customer')
		));
	}

	public function smsAction(){
		$user_id = get_user_id();	
		$this->getOptions();
		
		$cus_ids = get('customer_id',array(),true);
		
		if( count($cus_ids) > 0 ){
			$x=array();
			foreach( $cus_ids as $k ){
				$x[] = "'$k'";
			}
			
			$x = array_unique($x);
			$x = implode(',',$x);
			
			if( $this->hasRole('crm_admin') ){
				$customers = $this->Model->fetchAll("SELECT `name`,`ID` FROM `crm_customers`
					WHERE `ID` IN ($x) AND `is_draft`='no'");	
			}else{
				$customers = $this->Model->fetchAll("SELECT `name`,`ID` FROM `crm_customers`
					WHERE `ID` IN ($x) AND `is_draft`='no' AND '$user_id' IN (`created_by_id`,`care_by_id`)");
			}	
			
			$this->set(array(
				customers => $customers
			));				
			
		}else{
			return $this->setJSON(array(
				alert	=> 'Chưa có bản ghi nào được chọn'
			));
		}		
		
		if( isPost() ){
			loadClass('ZData');
			$f = new ZData();
			$f->addFields(array(
				sms_content	=> array(
					type			=> 'CHAR',
					label			=> 'Nội dung',
					max_length		=> 160,
					no_empty		=> true
				)		
			));
			
			$data = $f->getData();		
			
			if( !is_array($data) ){
				return $this->setJSON(array(
					alert	=> $data
				));
			}		
		
			if( $this->hasRole('crm_admin') ){
				$contacts = $this
					->Model
					->fetchAll("SELECT 
							`a`.`mobile`,
							`a`.`customer_id`
						FROM `crm_contacts` as `a`
						LEFT JOIN `crm_customers` as `b`
							ON `a`.`customer_id`=`b`.`ID`
						WHERE 
							`b`.`ID` IN ($x) 
							AND `a`.`mobile`<>''
							AND `a`.`is_draft`='no'");	
			}else{
				$contacts = $this
					->Model
					->fetchAll("SELECT 
							`a`.`mobile`,
							`a`.`customer_id`
						FROM `crm_contacts` as `a`
						LEFT JOIN `crm_customers` as `b`
							ON `a`.`customer_id`=`b`.`ID`
						WHERE 
							`b`.`ID` IN ($x) 
							AND '$user_id' IN (`b`.`created_by_id`,`b`.`care_by_id`)
							AND `a`.`mobile`<>''
							AND `a`.`is_draft`='no'");			
			}	
			
			foreach( $contacts as $post ){
				if( is_cellphone($post['mobile']) ){
					sendSMS(array(
						content			=>	get('sms_content'),
						user_id			=>	$user_id,
						address			=>	$post['mobile'],
						date_created	=>	new Model_Expr('NOW()'),
						date_send		=>	new Model_Expr('NOW()'),
						mode			=>	'crm_customer',
						post_id			=>	$post['customer_id']	
					),$this->Model);
					
					$this->Model->insert('crm_transactions',array(
						date_created 	=> new Model_Expr('NOW()'),
						date_updated 	=> new Model_Expr('NOW()'),
						updated_by_id 	=> get_user_id(),
						title 			=> 'Tin SMS giao dịch',
						desc 			=> $data['sms_content'],
						'date' 			=> new Model_Expr('NOW()'),			
						customer_id 	=> $post['customer_id'],			
						parent_id 		=> 0			
					));					
				}				
			}						
			
			return $this->setJSON(array(
				close	=> true,
				alert	=> 'Tin nhắn của bạn đã được gửi di'
			));
		}
	}

	public function smscontactAction(){
		$user_id = get_user_id();	
		$this->getOptions();
		
		$ids = get('ID',array(),true);
		
		if( count($ids) == 0 ){
			return $this->setJSON(array(
				alert	=> 'Chưa có bản ghi nào được chọn'
			));		
		}	
			
		$x=array();
		foreach( $ids as $k ){
			$x[] = "'$k'";
		}
		
		$x = array_unique($x);
		$x = implode(',',$x);
		
		if( $this->hasRole('crm_admin') ){
			$posts = $this->Model->fetchAll("SELECT `mobile` FROM `crm_contacts`
				WHERE `ID` IN ($x) AND `is_draft`='no'");	

		}else{
			//echo "aaa";
			$posts = $this->Model->fetchAll("SELECT `mobile` FROM `crm_contacts`
				WHERE `ID` IN ($x) AND `is_draft`='no' AND '$user_id' IN (`created_by_id`,`care_by_id`)");
		}	
		
		if( count($posts) == 0 ){
			return $this->setJSON(array(
				alert	=> 'Chưa có bản ghi nào được chọn'
			));		
		}			
		//die(var_dump($posts));
		if( isPost() ){
			//return;
			loadClass('ZData');
			$f = new ZData();
			$f->addFields(array(
				sms_content	=> array(
					type			=> 'CHAR',
					label			=> 'Nội dung',
					max_length		=> 160,
					no_empty		=> true
				)		
			));
			
			$data = $f->getData();		
			
			if( !is_array($data) ){
				return $this->setJSON(array(
					alert	=> $data
				));
			}
			
			foreach( $posts as $post ){
				if( is_cellphone($post['mobile']) ){
					sendSMS(array(
						content			=>	get('sms_content'),
						user_id			=>	$user_id,
						address			=>	$post['mobile'],
						date_created	=>	new Model_Expr('NOW()'),
						date_send		=>	new Model_Expr('NOW()'),
						mode			=>	'crm_customer',
						post_id			=>	$post['customer_id']	
					),$this->Model);
					
					$this->Model->insert('crm_transactions',array(
						date_created 	=> new Model_Expr('NOW()'),
						date_updated 	=> new Model_Expr('NOW()'),
						updated_by_id 	=> get_user_id(),
						title 			=> 'Tin SMS giao dịch',
						desc 			=> $data['sms_content'],
						'date' 			=> new Model_Expr('NOW()'),			
						customer_id 	=> $post['customer_id'],			
						parent_id 		=> 0			
					));					
				}				
			}						
			
			return $this->setJSON(array(
				close	=> true,
				alert	=> 'Tin nhắn của bạn đã được gửi di'
			));
		}
	}

}?>